<?php
/**
 * 数据库辅助类
 * 提供数据库连接和操作方法
 */
class Database {
    private static $instance = null;
    private $conn;
    
    /**
     * 构造函数，创建数据库连接
     */
    private function __construct() {
        try {
            $dsn = "mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=".DB_CHARSET;
            $options = [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES => false,
            ];
            $this->conn = new PDO($dsn, DB_USERNAME, DB_PASSWORD, $options);
        } catch (PDOException $e) {
            // 记录错误但不暴露具体信息
            error_log("Database Connection Error: " . $e->getMessage());
            throw new Exception("数据库连接失败，请检查配置或联系管理员。");
        }
    }
    
    /**
     * 获取数据库实例（单例模式）
     */
    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    public function getConnection() {
        return $this->conn;
    }
    
    /**
     * 执行SQL查询
     * @param string $sql SQL语句
     * @param array $params 参数数组
     * @return PDOStatement
     */
    public function query($sql, $params = []) {
        try {
            $stmt = $this->conn->prepare($sql);
            $stmt->execute($params);
            return $stmt;
        } catch (PDOException $e) {
            error_log("Query Error: " . $e->getMessage() . " - SQL: " . $sql);
            throw new Exception("查询执行失败，请联系管理员。");
        }
    }
    
    /**
     * 获取单条记录
     * @param string $sql SQL语句
     * @param array $params 参数数组
     * @return array|false 结果数组或false
     */
    public function getRow($sql, array $params = []) {
        $stmt = $this->query($sql, $params);
        return $stmt->fetch();
    }
    
    /**
     * 获取多条记录
     * @param string $sql SQL语句
     * @param array $params 参数数组
     * @return array 结果数组
     */
    public function getRows($sql, array $params = []) {
        $stmt = $this->query($sql, $params);
        return $stmt->fetchAll();
    }
    
    /**
     * 获取单个值
     * @param string $sql SQL语句
     * @param array $params 参数数组
     * @return mixed 结果值
     */
    public function getValue($sql, array $params = []) {
        $stmt = $this->query($sql, $params);
        return $stmt->fetchColumn();
    }
    
    /**
     * 插入记录
     * @param string $table 表名
     * @param array $data 数据数组
     * @return int 插入的ID
     */
    public function insert($table, array $data) {
        $fields = array_keys($data);
        $placeholders = array_fill(0, count($fields), '?');
        
        $sql = "INSERT INTO " . $table . " (" . implode(', ', $fields) . ") 
                VALUES (" . implode(', ', $placeholders) . ")";
        
        $this->query($sql, array_values($data));
        return $this->conn->lastInsertId();
    }
    
    /**
     * 更新记录
     * @param string $table 表名
     * @param array $data 数据数组
     * @param string $where 条件语句
     * @param array $params 参数数组
     * @return int 受影响的行数
     */
    public function update($table, array $data, $where, array $params = []) {
        $set = [];
        foreach ($data as $field => $value) {
            $set[] = $field . ' = ?';
        }
        
        $sql = "UPDATE " . $table . " SET " . implode(', ', $set) . " WHERE " . $where;
        
        $stmt = $this->query($sql, array_merge(array_values($data), $params));
        return $stmt->rowCount();
    }
    
    /**
     * 删除记录
     * @param string $table 表名
     * @param string $where 条件语句
     * @param array $params 参数数组
     * @return int 受影响的行数
     */
    public function delete($table, $where, array $params = []) {
        $sql = "DELETE FROM " . $table . " WHERE " . $where;
        $stmt = $this->query($sql, $params);
        return $stmt->rowCount();
    }
    
    // 执行更新/插入/删除操作并返回受影响的行数
    public function execute($sql, $params = []) {
        try {
            $stmt = $this->conn->prepare($sql);
            $stmt->execute($params);
            return $stmt->rowCount();
        } catch (PDOException $e) {
            error_log("Execute Error: " . $e->getMessage() . " - SQL: " . $sql);
            throw new Exception("操作执行失败，请联系管理员。");
        }
    }
    
    // 获取最后插入的ID
    public function lastInsertId() {
        return $this->conn->lastInsertId();
    }
}

// 提供Database类作为DatabaseHelper的别名，确保向后兼容
if (!class_exists('Database')) {
    class_alias('Database', 'DatabaseHelper');
} 